<template>
	<view class="normal-login-container">
		<view>

		</view>
		<view>
			<view class="wave"></view>
			<view class="wave"></view>
			<view class="wave"></view>
		</view>
		<view>
			<view class="logo-content align-center justify-center ">
				<image style="width: 300rpx;height: 100rpx;" :src="globalConfig.appInfo.logo" mode="widthFix">
				</image>
				<br>
				<text class=" font-title">瓜瓜通用程序移动端</text>
			</view>
			<view class="login-form-content" style="margin-top: 200rpx;">
				<!-- <view class="input-item flex align-center">
					<view class="iconfont icon-user icon"></view>
					<input v-model="loginForm.principal" class="input" type="text" placeholder="请输入账号" maxlength="30" />
				</view>
				<view class="input-item flex align-center">
					<view class="iconfont icon-password icon"></view>
					<input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码"
						maxlength="20" />
				</view> -->
				<!-- <view class="input-item flex align-center" style="width: 60%;margin: 0px;" v-if="captchaEnabled">
					<view class="iconfont icon-code icon"></view>
					<input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
					<view class="login-code">
						<image :src="codeUrl" @click="getCode" class="login-code-img"></image>
					</view>
				</view> -->

				<view class="action-btn">

					<!-- <button v-if="webType!=0" @click="handleLogin" plain type="primary" class="round">账号密码登录</button>
					<button v-if="webType==0" @click="handleLogin" class="login-btn cu-btn block bg-pink lg round"
						style="font-size: 38rpx;">账号密码登录</button> -->

					<!-- <button v-if="webType==2" @click="ddLogin" type="primary"
						class="login-btn cu-btn block bg-pink lg round">
						钉钉登录</button> -->
					<button @click="goIndex" plain class="round margin-top-xl border-custom bg-pink">暂不登录</button>
					<!--  #ifdef MP-WEIXIN -->
					<button @getuserinfo="getUserInfo" open-type="getUserInfo"
						class=" cu-btn block bg-pink lg round margin-top">
						快速登录</button>
						<!-- #endif -->

					<!-- #ifdef H5 -->
					<button @click="callBackUrl" class=" cu-btn block bg-pink lg round margin-top">
						快速登录</button>
						<!-- #endif -->


				</view>

				<view class="reg text-center" v-if="register">
					<text class="text-grey1">没有账号？</text>
					<text @click="handleUserRegister" class="text-blue">立即注册</text>
				</view>

				<view class="xieyi text-center">
					<text class="text-grey1">登录即代表同意</text>
					<text @click="handleUserAgrement" class="text-blue">《用户协议》</text>
					<text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
				</view>
			</view>
		</view>


	</view>
</template>

<script>
	import {
		setcommon
	} from '@/utils/common'

	import {
		getToken,
		setToken,
		removeToken
	} from '@/utils/auth'
	import {
		GetCode,
		isDD
	} from "@/utils/dingding.js"
	import {
		isNull
	} from '../utils/validate'
	import {
		getCodeImg,
		callBackUrl,
		getAccess_tokenAdnOpenidByCode,
		ddGetUserByCode,
		createGetOpenIdUrl,
		weMiniLogin,
		WeChatMpLogin
	} from '@/api/login'
	import {
		uuid
	} from '@/utils/auth.js'
	import storage from '@/utils/storage'
	export default {
		data() {
			return {
				webType: 0, //0 浏览器 1 微信 2 钉钉
				codeUrl: "",
				captchaEnabled: true,
				// 用户注册开关
				register: false,
				globalConfig: getApp().globalData.config,
				loginForm: {
					principal: "",
					password: "",
					verificationCode: "",
					uuid: "",
					loginFrom: "0"
				},
				datass: {
					corpid: "" //钉钉参数
				}

			}
		},
		created() {

		},
		onLoad(data) {
			if (isDD()) {
				this.webType = 2
			}
			this.checkLogin()
			this.init2()
		},

		methods: {
			checkLogin() {
				let token = getToken();

				if (!isNull(token)) {
					this.loginSuccess()
				}
			},

			async ddLogin() {

				if (isDD()) {
					this.webType = 2
					let adf = await GetCode()

					let corpid = this.getCodeFromUrl2("corpid", window.location.href)
					const {
						data
					} = await ddGetUserByCode({
						code: adf,
						corpid: corpid
					})

					await this.$store.dispatch('WeChatLogin', data)
					await this.$store.dispatch('getMenu')
					this.$modal.closeLoading()
					this.loginSuccess()
				}
			},
			getCodeFromUrl(url) {
				const searchParams = new URLSearchParams(url.split('?')[1]);
				return searchParams.get('code');
			},

			getCodeFromUrl2(code, url) {
				let searchParams = new URLSearchParams(url.split('?')[1]);

				searchParams = searchParams.get(code);
				searchParams = searchParams.replace(/[#\/]/g, ''); // 使用正则表达式替换所有的#字符为空字符串
				return searchParams
			},


			// 获取用户信息
			getUserInfo(e) {
				uni.showLoading({
					title: "加载中"
				})



				if (e.mp.detail.userInfo) {
					this.userInfo = e.mp.detail.userInfo;
					this.hasUserInfo = true;
					this.weMiniLogin();
				} else {
					uni.showModal({
						title: '提示',
						content: '您点击了拒绝授权',
						showCancel: false,
						confirmText: '返回授权',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击了“返回授权”');
							}
						}
					});
				}
			},


			// 登录并获取用户信息
			weMiniLogin() {
				let _this = this
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						// 登录成功，获取用户code
						const {
							code
						} = loginRes;

						console.log(code);
						// 发送code到后台换取openId, sessionKey, unionId
						_this.weMiniGetOpenId(code)

					},
					fail: (err) => {
						console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err);
						uni.showToast({
							title: '登录失败',
							icon: 'none'
						});
					}
				});
			},
			/** 
			 * 小程序登录
			 * @param {Object} code2
			 */
			async weMiniGetOpenId(code2) {
				const {
					data,
					code,
					msg
				} = await weMiniLogin(code2)


				if (data) {
					await this.$store.dispatch('decryptedDesPassWord', data)
					this.loginSuccess()
				} else {
					uni.showToast({
						title: '登录失败',
						icon: 'none'
					});
				}
			},


			init2() {

				//检测当前是否是微信环境
				if (/MicroMessenger/i.test(navigator.userAgent)) {
					this.webType = 1
				} else {

				}

				let code = this.getCodeFromUrl(window.location.href)
				if (!isNull(code)) {
					this.getAccess_tokenAdnOpenidByCode2(code)
				}
			},
			// 用户注册
			handleUserRegister() {
				this.$tab.redirectTo(`/pages/register`)
			},
			// 隐私协议
			handlePrivacy() {
				let site = this.globalConfig.appInfo.agreements[0]
				this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
			},
			// 用户协议
			handleUserAgrement() {
				let site = this.globalConfig.appInfo.agreements[1]
				this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
			},
			// 获取图形验证码
			getCode() {
				getCodeImg().then(res => {
					this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
					if (this.captchaEnabled) {
						this.codeUrl = 'data:image/gif;base64,' + res.img
					}
				})
			},

			handleWeChatLogin() {
				this.weMiniLogin()
			},

			//小程序登录
			//h5登录
			callBackUrl() {

				// window.location.href =
				// 	'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxadc06f06ab3ae6ad&redirect_uri=https%3A%2F%2Fvip.grasswave.cn%2Ftiaozhuan.html%3Furl%3Dhttp%253A%252F%252Frun.m.58it.cn%252F%2523%252Fpages%252Flogin&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
				window.location.href =
					'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxadc06f06ab3ae6ad&redirect_uri=https%3A%2F%2Fvip.grasswave.cn%2Ftiaozhuan.html%3Furl%3Dhttp%253A%252F%252Flocalhost%253A9090%252F%2523%252Fpages%252Flogin&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';



			},

			async getAccess_tokenAdnOpenidByCode2(code) {
				console.log("code" + code);
				const {
					data
				} = await WeChatMpLogin({
					code: code
				})
				console.log(data);

				await this.$store.dispatch('decryptedDesPassWord', data)
				this.$modal.closeLoading()
				this.loginSuccess()
			},
			// 登录方法
			async handleLogin() {
				if (this.loginForm.principal === "") {
					this.$modal.msgError("请输入您的账号")
				} else if (this.loginForm.password === "") {
					this.$modal.msgError("请输入您的密码")
				} else {
					this.$modal.loading("登录中...")
					this.pwdLogin()
				}
			},
			// 密码登录
			async pwdLogin() {
				this.loginForm.uuid = uuid()


				await this.$store.dispatch('Login', this.loginForm)
				await this.$store.dispatch('getMenu')
				this.$modal.closeLoading()
				this.loginSuccess()
			},
			goIndex() {
				this.$tab.reLaunch('/pages/index')
			},
			// 登录成功后，处理函数
			async loginSuccess(result) {
				// 设置用户信息
				this.$store.dispatch('GetInfo').then(res => {
					this.$tab.reLaunch('/pages/index')
				})
			}
		}
	}
</script>







<style lang="scss">
	// page {
	// 	background-color: #ffffff;
	// }

	.normal-login-container {
		width: 100%;

		.logo-content {
			width: 100%;
			font-size: 21px;
			text-align: center;
			padding-top: 15%;

			image {
				border-radius: 4px;
			}

			.title {
				color: #fff;
				margin-left: 10px;
			}
		}

		.login-form-content {
			text-align: center;
			margin: 20px auto;
			margin-top: 15%;
			width: 80%;

			.input-item {
				margin: 20px auto;
				background-color: #f5f6f7;
				height: 45px;
				border-radius: 20px;

				.icon {
					font-size: 38rpx;
					margin-left: 10px;
					color: #999;
				}

				.input {
					width: 100%;
					font-size: 14px;
					line-height: 20px;
					text-align: left;
					padding-left: 15px;
				}

			}

			.login-btn {
				margin-top: 40px;
				height: 45px;
			}

			.reg {
				margin-top: 15px;
			}

			.xieyi {
				color: #333;
				margin-top: 20px;
			}

			.login-code {
				height: 38px;
				float: right;

				.login-code-img {
					height: 38px;
					position: absolute;
					margin-left: 10px;
					width: 200rpx;
				}
			}
		}
	}
</style>